import axios, { AxiosRequestConfig } from 'axios';
// const md5 = require('crypto-js/md5');
import { ElMessage } from 'element-plus';
const instance = axios.create({
    withCredentials: false,
    baseURL: 'http://172.19.249.90:8084',
    timeout: 60 * 1000,
});
// http://172.19.70.212:8084/
let loadingInstance;

instance.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('TOKEN');
        // console.log(token, window.location.pathname);
        if (token) {
            config.headers['Authorization'] = token;
            // config.headers['verifyurl'] = md5(window.location.pathname);
        }
        // if (config.method === 'get' || config.method === 'GET') {
        //     loadingInstance = ElLoading.service({
        //         text: '加载中...',
        //         background: 'rgba(0, 0, 0, 0)',
        //     });
        // }

        // console.info('开始请求', config.url, config.data || config.params);
        return config;
    },
    (error) => {
        loadingInstance && loadingInstance.close();
        // console.log('request', error);
        return Promise.reject(error);
    },
);

instance.interceptors.response.use(
    (response) => {
        loadingInstance && loadingInstance.close();
        // console.info('结束请求', response.config.url, response.data);
        // 二进制数据则直接返回
        if (
            response.request.responseType === 'blob' ||
            response.request.responseType === 'arraybuffer'
        ) {
            return response.data;
        }
        const res = response.data;
        // const reLoginCode = ['50009', '500010', '401', '50008', '50012', '50014', '5001001'];
        // const responseCode = response?.data?.code || response?.data?.data?.code || response.status;
        // if (response.status === 501 || reLoginCode.includes(`${responseCode}`)) {
        //     ElMessageBox.confirm('登录信息已过期，请重新打开该页面')
        //         .then(() => {
        //             localStorage.removeItem('TOKEN');
        //             window.location.href = '/login';
        //         })
        //         .catch(() => {
        //             console.log('cancel');
        //         });
        // }

        // 网络请求响应异常
        if (response.status !== 200) {
            ElMessage.error('当前系统繁忙，请稍后再试');
            return Promise.reject(res.msg || 'Error');
        }

        // if (res.code === 0 || res.code === '0') {
        //     if (res.data.code === '500011') {
        //         ElMessageBox.confirm(res.data.msg, '登录失败', {
        //             confirmButtonText: '重新登录',
        //             cancelButtonText: '取消',
        //             type: 'warning',
        //         })
        //             .then(() => {
        //                 localStorage.removeItem('TOKEN');
        //                 window.location.href = '/login';
        //             })
        //             .catch(() => {
        //                 console.log('cancel');
        //             });
        //     }
        //     return Promise.resolve(res.data);
        // }
        return Promise.resolve(res);
        // return Promise.reject(res);
    },
    (error) => {
        loadingInstance && loadingInstance.close();
        // console.log('err' + error);
        if (JSON.stringify(error).indexOf('timeout')) {
            ElMessage.error('请求超时，请重试');
            return;
        }
        ElMessage.error('当前系统繁忙，请稍后再试');
        throw new Error(error);
    },
);

function requestService<P = AxiosRequestConfig['data'], R = any>(
    path: string,
    params?: P,
    options: AxiosRequestConfig = {},
) {
    const realOptions = {
        url: path,
        method: 'POST',
        ...options,
    };

    if (realOptions.method === 'GET') {
        realOptions.params = params;
    } else {
        realOptions.data = params;
    }

    return instance(realOptions) as Promise<R>;
}
export default requestService;
